package br.ufpe.cin.mac.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

/**
 * Class Marshal
 * 
 * @author Osmany
 * @author Rafael Roque
 *
 */

public class Marshal {
	
	public static Object[] recoverObjectArray(byte[][] serializedObjectArray) throws IOException, ClassNotFoundException{
		if(serializedObjectArray == null){
			return null;
		}
		int arrayLengh = serializedObjectArray.length;
		Object[] ret = new Object[arrayLengh];
		for(int i = 0; i < arrayLengh; i++){
			ret[i] = recoverObject(serializedObjectArray[i]);
		}
		return ret;	
	}
	
	public static Object recoverObject(byte[] serializedObject) throws IOException, ClassNotFoundException{
		ByteArrayInputStream bin = new ByteArrayInputStream(serializedObject);
		ObjectInputStream oin = new ObjectInputStream(bin);
		return oin.readObject();
	}
	
	public static byte[] serializeObject(Object obj) throws IOException{
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		ObjectOutputStream oout = new ObjectOutputStream(bout);
		oout.writeObject(obj);
		return bout.toByteArray();	
	}
	
	public static byte[][] serializeObjectArray(Object[] objs) throws IOException{
		int arrayLengh = objs.length;
		byte[][] ret = new byte[arrayLengh][];
		for(int i = 0; i < arrayLengh; i++){
			ret[i] = serializeObject(objs[i]);
		}
		return ret;		
	}
	
	public static String recoverString(byte[] serializedString) throws CharacterCodingException {
		Charset charset = Charset.forName("ISO-8859-1");  
		CharsetDecoder decoder = charset.newDecoder();  
		CharBuffer buf = decoder.decode(ByteBuffer.wrap(serializedString));
		return buf.toString();		
	}
	
	public static byte[] serializeString(String str) throws CharacterCodingException{
		Charset charset = Charset.forName("ISO-8859-1");  
		CharsetEncoder encoder = charset.newEncoder();  
		ByteBuffer bb = encoder.encode(CharBuffer.wrap(str)); 
		return bb.array();
	}
	
	public static byte[][] serializeStringArray(String[] strs) throws CharacterCodingException{
		int arrayLengh = strs.length;
		byte[][] ret = new byte[arrayLengh][];
		for(int i = 0; i < arrayLengh; i++){
			ret[i] = serializeString(strs[i]);
		}
		return ret;	
	}
	
	public static String[] recoverStringArray(byte[][] serializedStringArray) throws CharacterCodingException{
		int arrayLengh = serializedStringArray.length;
		String[] ret = new String[arrayLengh];
		for(int i = 0; i < arrayLengh; i++){
			ret[i] = recoverString(serializedStringArray[i]);
		}
		return ret;	
	}

}
